package zkdemo;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.barriers.DistributedBarrier;
import org.apache.curator.framework.recipes.barriers.DistributedDoubleBarrier;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.Before;
import org.junit.Test;

public class Curator_DistBarrier {
	CuratorFramework client;
	
	@Before
	public void init() {
		client = CuratorFrameworkFactory.builder()
				.connectString("192.168.10.188:2181")
				.sessionTimeoutMs(5000)
				.connectionTimeoutMs(3000)
				.retryPolicy(new ExponentialBackoffRetry(1000, 3))
				.namespace("zk-book")
				.build();
		client.start();
	}
	
	static DistributedBarrier distBarrier;
	@Test
	public void test() throws Exception {
		distBarrier = new DistributedBarrier(client, "/dist_barrier");
		for (int i = 0; i < 5; i++) {
			new Thread(() -> {
				System.out.println(Thread.currentThread().getName()+" 号barrier设置");
				try {
					distBarrier.setBarrier();
					distBarrier.waitOnBarrier();
				} catch (Exception e) {
					e.printStackTrace();
				}
				System.out.println(Thread.currentThread().getName()+"启动");
			}).start();
		}
		
		Thread.sleep(2000);
		distBarrier.removeBarrier();
		Thread.sleep(Long.MAX_VALUE);
	}
	
	@Test
	public void test2() throws Exception {
		for (int i = 0; i < 5; i++) {
			new Thread(() -> {
				DistributedDoubleBarrier distBarrier = new DistributedDoubleBarrier(client, "/dist_double_barrier", 5);
				System.out.println(Thread.currentThread().getName()+" 号barrier设置");
				try {
					Thread.sleep(1000);
					distBarrier.enter();
					System.out.println(Thread.currentThread().getName()+" 启动");
					Thread.sleep(1000);
					distBarrier.leave();
					System.out.println(Thread.currentThread().getName()+" 退出");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}).start();
		}
		
		Thread.sleep(Long.MAX_VALUE);
	}
}
